package com.clinic.web.servlets;

import java.io.IOException;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import java.util.ResourceBundle;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.clinic.web.util.Util;
import com.fasterxml.jackson.databind.ObjectMapper;

/**
 * Servlet implementation class Signup
 */
@WebServlet("/Register")
public class Register extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public Register() {
		super();
	}

	/**
	 * http://localhost:8091/web_layer/Register?email_address=labib.farag.saad@gmail.com&token=test
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		System.out.println("doPost");
	}

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		System.out.println("Enter - doGet in Register Servlet");
		ObjectMapper mapper = new ObjectMapper();
		String email_address = req.getParameter("email_address");
		String token = req.getParameter("token");
		
		Map<String, String> map = new HashMap<String, String>();
		map.put("email_address", email_address);
		map.put("token", token);
		String jsonvalidate = mapper.writeValueAsString(map);
		
		// call post method with JSON format.
		ResourceBundle server = ResourceBundle.getBundle("com/clinic/web/prop/clinicServices", Locale.getDefault());
		String result = Util.POST_Method(server.getString("serverURL") + "patientservices/validate", jsonvalidate);
		if(result.equals("Valid")){
			req.setAttribute("msg","Validated, Please try to Signup now" );
			System.out.println("Exit - doGet in Register Servlet");
			RequestDispatcher dispatcher = req.getServletContext().getRequestDispatcher("/signin.jsp");
			dispatcher.forward(req, resp);
		} else {
			System.out.println("Exit - doGet in Register Servlet");
			resp.sendRedirect("notvalid.jsp");
		}
	}
}